import { Container } from "../Container";
import { BaseGui } from "../Services/BaseGui";
import { ModelManService } from "../Services/ModelManService";
import { ViewerService } from "../Services/ViewerService";

export class TestGui extends BaseGui {
    title: string = `试验方法[${TestGui.name}]`;
    Level = 1;
    private ModelManService = Container.defineProperty(ModelManService);
    private ViewerService = Container.defineProperty(ViewerService);
    protected async UpdateGui() {
        let fun = {
            updateModelItems: async () => {
                let temp = this.ViewerService.viewer.getAllModels().map(async (_) => {
                    let temp = this.ModelManService.getModelInfo(_) as any;
                    temp.modelItems = await this.searchOBJCodeMapping(_);
                });
                await Promise.all(temp);
                alert("执行完毕!");
            },
            offline: () => {
                let dir = window.prompt("fs路径");
                if (dir) {
                    let jobs = this.ModelManService.getData().modelLayers.map(_ => {
                        let index = _.url.indexOf("jobs/");
                        _.url = _.url.substring(index);
                        return _.url.split("/")[1];
                    });
                    let str = jobs.map(_ => `${dir}\\jobs\\${_}`).join(" ");
                    console.log(str);
                    alert("请查看日志");
                }
            }
        };
        let gui = this.gui;
        let updateGUI = () => {
            Array.from(gui.__controllers).forEach(_ => {
                gui.remove(_);
            });
            this.guiService.buildGUIByObject(this.gui, fun);
        };
        updateGUI();
    }

    private async searchOBJCodeMapping(model: Sippreep.Viewing.Model) {
        return await this.ViewerService.userFunction(model, (pdb) => {
            let code2dbId: { [code: string]: { dbId: number, code: string, name: string, type: string, group: string } } = {};
            let getValue = (objProp: Sippreep.Viewing.PropertyResult, attrName: string) => {
                let p = objProp.properties.find(v => v.attributeName == attrName);
                return p ? p.displayValue : null;
            }
            pdb.enumObjects((dbId: number) => {
                let objProp = pdb.getObjectProperties(dbId, ["OBJCode", "OBJName", "OBJType", "OBJGroup"]);
                if (!objProp)
                    return;
                let code = getValue(objProp, "OBJCode")!;
                let name = getValue(objProp, "OBJName")!;
                let type = getValue(objProp, "OBJType")!;
                let group = getValue(objProp, "OBJGroup")!;
                if (code != null) {
                    code2dbId[code] = { dbId, code, name, type, group }
                }
            });
            return Object.values(code2dbId).sort((x: any, y: any) => {
                return x.code > y.code ? 1 : -1;
            });
        }, null);
    }
}
